<template>
  <div class="student-grades-container">
    <!-- 顶部区域 -->
    <div class="page-header">
      <div class="header-content">
        <h1>{{ currentStudent?.name || '学生' }}的成绩详情</h1>
        <div class="header-decoration"></div>
      </div>
      <div class="button-group">
        <template v-if="isTeacher">
          <el-button type="primary" @click="handleAdd" :icon="Plus">新增成绩</el-button>
          <el-button type="warning" @click="handleEdit" :icon="Edit">编辑成绩</el-button>
          <el-button type="danger" @click="handleDelete" :icon="Delete">删除成绩</el-button>
        </template>
        <el-button type="info" @click="handleLogout" :icon="SwitchButton">退出登录</el-button>
      </div>
    </div>

    <!-- 统计卡片区域 -->
    <div class="stats-section">
      <el-row :gutter="20" class="stat-cards">
        <el-col :span="6">
          <el-card class="stat-card" :body-style="{ padding: '0px' }">
            <div class="stat-card-content">
              <div class="stat-icon-wrapper average">
                <el-icon>
                  <TrendCharts />
                </el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-label">平均分</div>
                <div class="stat-value">{{ calculateAverage() }}</div>
                <div class="stat-unit">分</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card" :body-style="{ padding: '0px' }">
            <div class="stat-card-content">
              <div class="stat-icon-wrapper highest">
                <el-icon>
                  <ArrowUp />
                </el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-label">最高分</div>
                <div class="stat-value">{{ calculateHighest() }}</div>
                <div class="stat-unit">分</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card" :body-style="{ padding: '0px' }">
            <div class="stat-card-content">
              <div class="stat-icon-wrapper lowest">
                <el-icon>
                  <ArrowDown />
                </el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-label">最低分</div>
                <div class="stat-value">{{ calculateLowest() }}</div>
                <div class="stat-unit">分</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card" :body-style="{ padding: '0px' }">
            <div class="stat-card-content">
              <div class="stat-icon-wrapper total">
                <el-icon>
                  <Reading />
                </el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-label">科目数</div>
                <div class="stat-value">{{ currentStudent?.grades?.length || 0 }}</div>
                <div class="stat-unit">门</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 学期统计卡片 -->
    <div class="semester-section">
      <el-card class="semester-card">
        <template #header>
          <div class="semester-header">
            <h3>成绩统计</h3>
            <el-select v-model="selectedSemester" placeholder="选择学期" @change="handleSemesterChange"
              style="width: 400px;">
              <el-option v-for="semester in semesters" :key="semester" :label="semester" :value="semester" />
            </el-select>
          </div>
        </template>
        <el-row :gutter="20">
          <el-col :span="12" v-for="(stat, index) in semesterStats" :key="index">
            <div class="semester-stat-item">
              <div class="semester-stat-label">{{ stat.label }}</div>
              <div class="semester-stat-value">{{ stat.value }}</div>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </div>

    <!-- 学生信息卡片 -->
    <div class="info-section">
      <el-card class="info-card">
        <template #header>
          <div class="info-header">
            <h3>学生基本信息</h3>
          </div>
        </template>
        <el-table :data="currentStudent ? [currentStudent] : []" style="width: 100%;">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="studentId" label="学号" width="120"></el-table-column>
          <el-table-column prop="name" label="姓名" width="120"></el-table-column>
          <el-table-column prop="gender" label="性别" width="80"></el-table-column>
          <el-table-column prop="age" label="年龄" width="80"></el-table-column>
          <el-table-column prop="class" label="班级"></el-table-column>
          <el-table-column prop="contact" label="联系方式" width="150"></el-table-column>
          <el-table-column prop="totalScore" label="总成绩" width="100"></el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <!-- 主要图表区域 -->
      <div class="main-charts">
        <el-row :gutter="20">
          <el-col :span="16">
            <el-card class="chart-card main-chart">
              <template #header>
                <div class="chart-header">
                  <h3>成绩热力图</h3>
                  <div class="chart-actions">
                    <el-tooltip content="查看详细数据" placement="top">
                      <el-button type="text" :icon="DataLine" circle></el-button>
                    </el-tooltip>
                  </div>
                </div>
              </template>
              <div ref="heatChart" class="chart main-chart-content"></div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-header">
                  <h3>成绩箱线图</h3>
                  <div class="chart-actions">
                    <el-tooltip content="查看详细数据" placement="top">
                      <el-button type="text" :icon="DataLine" circle></el-button>
                    </el-tooltip>
                  </div>
                </div>
              </template>
              <div ref="boxChart" class="chart"></div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 次要图表区域 -->
      <div class="secondary-charts">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-header">
                  <h3>各科成绩柱状图</h3>
                  <div class="chart-actions">
                    <el-tooltip content="查看详细数据" placement="top">
                      <el-button type="text" :icon="DataLine" circle></el-button>
                    </el-tooltip>
                  </div>
                </div>
              </template>
              <div ref="barChart" class="chart"></div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-header">
                  <h3>成绩分布饼图</h3>
                  <div class="chart-actions">
                    <el-tooltip content="查看详细数据" placement="top">
                      <el-button type="text" :icon="DataLine" circle></el-button>
                    </el-tooltip>
                  </div>
                </div>
              </template>
              <div ref="pieChart" class="chart"></div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 第三行图表 -->
      <div class="tertiary-charts">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-header">
                  <h3>成绩趋势折线图</h3>
                  <div class="chart-actions">
                    <el-tooltip content="查看详细数据" placement="top">
                      <el-button type="text" :icon="DataLine" circle></el-button>
                    </el-tooltip>
                  </div>
                </div>
              </template>
              <div ref="lineChart" class="chart"></div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-header">
                  <h3>科目能力雷达图</h3>
                  <div class="chart-actions">
                    <el-tooltip content="查看详细数据" placement="top">
                      <el-button type="text" :icon="DataLine" circle></el-button>
                    </el-tooltip>
                  </div>
                </div>
              </template>
              <div ref="radarChart" class="chart"></div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 添加成绩弹窗 -->
    <el-dialog v-model="addDialogVisible" title="添加成绩" width="30%">
      <el-form :model="addForm" label-width="80px">
        <el-form-item label="科目" required>
          <el-input v-model="addForm.subject" placeholder="请输入科目名称" />
        </el-form-item>
        <el-form-item label="分数" required>
          <el-input-number v-model="addForm.score" :min="0" :max="100" style="width: 100%" />
        </el-form-item>
        <el-form-item label="学期" required>
          <el-select v-model="addForm.semester" placeholder="请选择学期" style="width: 100%">
            <el-option v-for="option in semesterOptions" :key="option.value" :label="option.label"
              :value="option.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAdd">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑成绩弹窗 -->
    <el-dialog v-model="editDialogVisible" title="编辑成绩" width="30%">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="选择科目" required>
          <el-select v-model="editForm._id" placeholder="请选择要编辑的科目" @change="handleSubjectSelect" style="width: 100%">
            <el-option v-for="grade in currentStudent?.grades || []" :key="grade._id" :label="grade.subject"
              :value="grade._id">
              <div class="grade-option">
                <div class="grade-info">
                  <span class="subject-name">{{ grade.subject }}</span>
                  <span class="semester-tag">{{ grade.semester }}</span>
                </div>
                <span class="score-info">当前分数: {{ grade.score }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分数" required>
          <el-input-number v-model="editForm.score" :min="0" :max="100" style="width: 100%" />
        </el-form-item>
        <el-form-item label="学期" required>
          <el-select v-model="editForm.semester" placeholder="请选择学期" style="width: 100%">
            <el-option v-for="option in semesterOptions" :key="option.value" :label="option.label"
              :value="option.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmEdit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 删除成绩弹窗 -->
    <el-dialog v-model="deleteDialogVisible" title="删除成绩" width="30%">
      <el-form :model="deleteForm" label-width="80px">
        <el-form-item label="选择科目" required>
          <el-select v-model="deleteForm.subjectId" placeholder="请选择要删除的科目" style="width: 100%">
            <el-option v-for="grade in currentStudent?.grades || []" :key="grade._id" :label="grade.subject"
              :value="grade._id">
              <div class="grade-option">
                <div class="grade-info">
                  <span class="subject-name">{{ grade.subject }}</span>
                  <span class="semester-tag">{{ grade.semester }}</span>
                </div>
                <span class="score-info">当前分数: {{ grade.score }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确定删除</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { ref, onMounted, computed } from 'vue';
import { ElMessage } from 'element-plus';
import {
  Plus,
  Edit,
  Delete,
  DataLine,
  TopRight,
  BottomLeft,
  Collection,
  TrendCharts,
  ArrowUp,
  ArrowDown,
  Reading,
  SwitchButton
} from '@element-plus/icons-vue';
import { useRoute, useRouter } from 'vue-router';

export default {
  // props: {
  //   id: {
  //     type: String,
  //     required: true
  //   }
  // },

  setup() {
    const router = useRouter();
    const route = useRoute();
    
    // 获取当前用户信息
    const currentUser = ref(JSON.parse(localStorage.getItem('user') || '{}'));
    
    // 判断是否为教师
    const isTeacher = computed(() => currentUser.value.role === 'teacher');
    
    // 判断是否为当前学生的账号
    const isCurrentStudent = computed(() => {
      return currentUser.value.role === 'user' && 
             currentUser.value.studentId === currentStudent.value.studentId;
    });

    // 检查权限
    const checkPermission = () => {
      if (!isTeacher.value && !isCurrentStudent.value) {
        ElMessage.error('您没有权限查看此页面');
        router.push('/dashboard');
      }
    };

    const barChart = ref(null);
    const pieChart = ref(null);
    const lineChart = ref(null);
    const radarChart = ref(null);
    const boxChart = ref(null);
    const heatChart = ref(null);

   
    const currentStudent = ref({
      studentId: '',
      name: '',
      gender: '',
      age: 0,
      class: '',
      contact: '',
      totalScore: 0
    });

    const addDialogVisible = ref(false);
    const semesterOptions = ref([
      { label: '第一学期', value: '第一学期' },
      { label: '第二学期', value: '第二学期' },
      { label: '第三学期', value: '第三学期' },
      { label: '第四学期', value: '第四学期' },
      { label: '第五学期', value: '第五学期' },
      { label: '第六学期', value: '第六学期' },
      { label: '第七学期', value: '第七学期' },
      { label: '第八学期', value: '第八学期' }
    ]);

    const addForm = ref({
      subject: '',
      score: '',
      semester: '第一学期'
    });

    const handleAdd = () => {
      addDialogVisible.value = true;
    };

    const calculateTotalScore = (grades) => {
      if (!grades || grades.length === 0) return 0;
      return grades.reduce((acc, grade) => acc + grade.score, 0);
    };

    const confirmAdd = async () => {
      try {
        const newGrade = {
          studentId: currentStudent.value.studentId,
          subject: addForm.value.subject,
          score: addForm.value.score,
          semester: addForm.value.semester
        };

        const response = await fetch('http://localhost:3000/grades', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(newGrade)
        });

        if (response.ok) {
          const addedGrade = await response.json();
          currentStudent.value.grades.push(addedGrade);
          currentStudent.value.totalScore = calculateTotalScore(currentStudent.value.grades);
          await fetch(`http://localhost:3000/students/${currentStudent.value.studentId}`, {
            method: 'PATCH',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({ totalScore: currentStudent.value.totalScore })
          });
          initCharts(currentStudent.value);
          ElMessage.success('成绩添加成功');
          addDialogVisible.value = false;
          addForm.value = {
            subject: '',
            score: '',
            semester: '第一学期'
          };
        } else {
          ElMessage.error('成绩添加失败');
        }
      } catch (error) {
        console.error('添加成绩失败:', error);
        ElMessage.error('添加成绩失败');
      }
    };

    const editDialogVisible = ref(false);
    const editForm = ref({
      _id: '',
      subject: '',
      score: '',
      semester: '第一学期'
    });

    const handleEdit = () => {
      if (!currentStudent.value.grades || currentStudent.value.grades.length === 0) {
        ElMessage.warning('没有可编辑的成绩');
        return;
      }

      // 重置编辑表单
      editForm.value = {
        _id: '',
        subject: '',
        score: '',
        semester: '第一学期'
      };

      // 显示编辑对话框
      editDialogVisible.value = true;
    };

    const confirmEdit = async () => {
      try {
        const updatedGrade = {
          _id: editForm.value._id,
          subject: editForm.value.subject,
          score: editForm.value.score,
          semester: editForm.value.semester
        };

        const response = await fetch(`http://localhost:3000/grades/${editForm.value._id}`, {
          method: 'PATCH',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(updatedGrade)
        });

        if (response.ok) {
          const editedGrade = await response.json();
          const index = currentStudent.value.grades.findIndex(g => g._id === editForm.value._id);
          if (index !== -1) {
            currentStudent.value.grades[index] = editedGrade;
            currentStudent.value.totalScore = calculateTotalScore(currentStudent.value.grades);
            await fetch(`http://localhost:3000/students/${currentStudent.value.studentId}`, {
              method: 'PATCH',
              headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({ totalScore: currentStudent.value.totalScore })
            });
            initCharts(currentStudent.value);
            ElMessage.success('成绩更新成功');
            editDialogVisible.value = false;
          }
        } else {
          ElMessage.error('成绩更新失败');
        }
      } catch (error) {
        console.error('编辑成绩失败:', error);
        ElMessage.error('编辑成绩失败');
      }
    };

    const selection = ref([]);
    const deleteDialogVisible = ref(false);
    const deleteForm = ref({
      subjectId: ''
    });

    const handleDelete = () => {
      if (!currentStudent.value.grades || currentStudent.value.grades.length === 0) {
        ElMessage.warning('没有可删除的成绩');
        return;
      }
      deleteDialogVisible.value = true;
    };

    const confirmDelete = async () => {
      try {
        const response = await fetch(`http://localhost:3000/grades/${deleteForm.value.subjectId}`, {
          method: 'DELETE'
        });

        if (response.ok) {
          const index = currentStudent.value.grades.findIndex(g => g._id === deleteForm.value.subjectId);
          if (index !== -1) {
            currentStudent.value.grades.splice(index, 1);
            currentStudent.value.totalScore = calculateTotalScore(currentStudent.value.grades);
            await fetch(`http://localhost:3000/students/${currentStudent.value.studentId}`, {
              method: 'PATCH',
              headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({ totalScore: currentStudent.value.totalScore })
            });
            initCharts(currentStudent.value);
            ElMessage.success('成绩删除成功');
            deleteDialogVisible.value = false;
            deleteForm.value = {
              subjectId: ''
            };
          }
        } else {
          ElMessage.error('成绩删除失败');
        }
      } catch (error) {
        console.error('删除成绩失败:', error);
        ElMessage.error('删除成绩失败');
      }
    };

    const getStudentData = async (id) => {
      try {
        const [studentRes, gradesRes] = await Promise.all([
          fetch(`http://localhost:3000/students/${id}`),
          fetch(`http://localhost:3000/grades?studentId=${id}`)
        ]);

        const student = await studentRes.json();
        const allGrades = await gradesRes.json();
        const grades = allGrades.filter(grade => grade.studentId === id);

        return {
          ...student,
          grades
        };
      } catch (error) {
        console.error('获取学生数据失败:', error);
        return null;
      }
    };

    const calculateAverage = () => {
      if (!currentStudent.value?.grades?.length) return '0';
      const sum = currentStudent.value.grades.reduce((acc, grade) => acc + grade.score, 0);
      return (sum / currentStudent.value.grades.length).toFixed(1);
    };

    const calculateHighest = () => {
      if (!currentStudent.value?.grades?.length) return '0';
      return Math.max(...currentStudent.value.grades.map(grade => grade.score));
    };

    const calculateLowest = () => {
      if (!currentStudent.value?.grades?.length) return '0';
      return Math.min(...currentStudent.value.grades.map(grade => grade.score));
    };

    const initCharts = (student) => {
      if (!student.grades || student.grades.length === 0) return;

      // 按科目分组成绩
      const subjectGroups = {};
      student.grades.forEach(grade => {
        if (!subjectGroups[grade.subject]) {
          subjectGroups[grade.subject] = [];
        }
        subjectGroups[grade.subject].push(grade);
      });

      // 获取当前学生的各科成绩
      const subjectScores = Object.entries(subjectGroups).map(([subject, grades]) => {
        return { subject, score: grades[0].score };
      });

      // 柱状图 - 各科原始成绩
      const barChartInstance = echarts.init(barChart.value);
      barChartInstance.setOption({
        tooltip: {},
        xAxis: {
          data: subjectScores.map(item => item.subject)//x轴显示科目名称
        },
        yAxis: {},
        series: [{
          name: '成绩',
          type: 'bar',
          data: subjectScores.map(item => item.score)
        }]
      });

      // 饼图 - 成绩分布
      const pieChartInstance = echarts.init(pieChart.value);
      pieChartInstance.setOption({
        tooltip: {
          trigger: 'item'
        },
        series: [{
          name: '成绩分布',
          type: 'pie',
          radius: '50%',
          data: [
            { value: subjectScores.filter(g => g.score >= 85).length, name: '优秀' },
            { value: subjectScores.filter(g => g.score >= 75 && g.score < 85).length, name: '良好' },
            { value: subjectScores.filter(g => g.score >= 60 && g.score < 75).length, name: '及格' },
            { value: subjectScores.filter(g => g.score < 60).length, name: '不及格' }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      });

      // 折线图 - 按学期显示成绩变化
      const lineChartInstance = echarts.init(lineChart.value);
      const semesterGroups = {};
      student.grades.forEach(grade => {
        if (!semesterGroups[grade.semester]) {
          semesterGroups[grade.semester] = [];//初始化每个学期的成绩数组
        }
        semesterGroups[grade.semester].push(grade);//将每个学期的成绩添加到对应的数组中
      });

      const semesterScores = Object.entries(semesterGroups)
        .sort((a, b) => a[0].localeCompare(b[0]))//按学期排序
        .map(([semester, grades]) => {
          return { semester, score: grades[0].score };
        });

      lineChartInstance.setOption({
        tooltip: {},
        xAxis: {
          type: 'category',//类目轴
          data: semesterScores.map(item => item.semester)
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: semesterScores.map(item => item.score),
          type: 'line'
        }]
      });

      // 雷达图 - 各科成绩表现
      const radarChartInstance = echarts.init(radarChart.value);
      radarChartInstance.setOption({
        tooltip: {},
        //坐标系配置
        radar: {
          // 维度指标,名称以及最大值
          indicator: subjectScores.map(grade => ({
            name: grade.subject,
            max: 100
          })),
          shape: 'circle',
          splitNumber: 5
        },
        series: [{
          name: '成绩',
          type: 'radar',
          data: [{
            value: subjectScores.map(grade => grade.score),
            name: '原始成绩'
          }],
          areaStyle: {
            color: 'rgba(64, 158, 255, 0.2)'
          },
          lineStyle: {
            width: 2
          }
        }]
      });

      // 箱线图
      const boxChartInstance = echarts.init(boxChart.value);
      const boxData = subjectScores.map(item => item.score);
      boxChartInstance.setOption({
        tooltip: {
          trigger: 'item',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '10%',
          right: '10%',
          bottom: '15%'
        },
        xAxis: {
          type: 'category',
          data: ['成绩分布'],
          boundaryGap: true,
          nameGap: 30,
          splitArea: {
            show: false
          },
          axisLabel: {
            show: false
          },
          splitLine: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          name: '分数',
          splitArea: {
            show: true
          }
        },
        series: [{
          name: '成绩分布',
          type: 'boxplot',
          datasetIndex: 0,
          data: [
            [
              Math.min(...boxData),
              calculateQuartile(boxData, 0.25),
              calculateQuartile(boxData, 0.5),
              calculateQuartile(boxData, 0.75),
              Math.max(...boxData)
            ]
          ],
          itemStyle: {
            color: '#409EFF',
            borderColor: '#67C23A'
          }
        }]
      });

      // 热力图
      const heatChartInstance = echarts.init(heatChart.value);
      const heatData = [];
      const subjects = subjectScores.map(item => item.subject);
      const semesters = [...new Set(student.grades.map(grade => grade.semester))].sort();

      semesters.forEach((semester, i) => {
        subjects.forEach((subject, j) => {
          const grade = student.grades.find(g => g.subject === subject && g.semester === semester);
          if (grade) {
            heatData.push([j, i, grade.score]);
          }
        });
      });

      heatChartInstance.setOption({
        tooltip: {
          position: 'top'
        },
        grid: {
          height: '50%',
          top: '10%'
        },
        xAxis: {
          type: 'category',
          data: subjects,
          splitArea: {
            show: true
          }
        },
        yAxis: {
          type: 'category',
          data: semesters,
          splitArea: {
            show: true
          }
        },
        visualMap: {
          min: 0,
          max: 100,
          calculable: true,
          orient: 'horizontal',
          left: 'center',
          bottom: '15%'
        },
        series: [{
          name: '成绩热力图',
          type: 'heatmap',
          data: heatData,
          label: {
            show: true
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      });
    };

    const calculateQuartile = (arr, q) => {
      const sorted = [...arr].sort((a, b) => a - b);
      const pos = (sorted.length - 1) * q;
      const base = Math.floor(pos);
      const rest = pos - base;
      if (sorted[base + 1] !== undefined) {
        return sorted[base] + rest * (sorted[base + 1] - sorted[base]);
      } else {
        return sorted[base];
      }
    };

    const selectedSemester = ref('');
    const semesters = ref([]);
    const semesterStats = ref([]);

    const calculateSemesterStats = (semester) => {
      if (!currentStudent.value?.grades) return [];

      const semesterGrades = currentStudent.value.grades.filter(g => g.semester === semester);

      const currentAvg = semesterGrades.reduce((acc, g) => acc + g.score, 0) / semesterGrades.length;

      return [
        {
          label: '学期平均分',
          value: currentAvg.toFixed(1)
        },
        {
          label: '最高科目',
          value: semesterGrades.length ?
            semesterGrades.reduce((max, g) => g.score > max.score ? g : max).subject : '-'
        }
      ];
    };

    const handleSemesterChange = () => {
      semesterStats.value = calculateSemesterStats(selectedSemester.value);
    };

    const initSemesterData = (student) => {
      if (!student?.grades) return;

      // 获取所有学期并按时间排序
      const allSemesters = [...new Set(student.grades.map(g => g.semester))].sort((a, b) => {
        const [yearA, termA] = a.split('-');
        const [yearB, termB] = b.split('-');
        return yearA === yearB ? termA - termB : yearA - yearB;
      });

      semesters.value = allSemesters;
      if (allSemesters.length > 0) {
        selectedSemester.value = allSemesters[allSemesters.length - 1]; // 默认选择最新学期
        semesterStats.value = calculateSemesterStats(selectedSemester.value);
      }
    };

    const handleSubjectSelect = (gradeId) => {
      const selectedGrade = currentStudent.value.grades.find(g => g._id === gradeId);
      if (selectedGrade) {
        editForm.value = {
          _id: selectedGrade._id,
          subject: selectedGrade.subject,
          score: selectedGrade.score,
          semester: selectedGrade.semester
        };
      }
    };

    const handleLogout = async () => {
      try {
        // 清除本地存储的token
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        
        // 显示退出成功消息
        ElMessage.success('退出登录成功');
        
        // 跳转到登录页面
        router.push('/login');
      } catch (error) {
        console.error('退出登录失败:', error);
        ElMessage.error('退出登录失败');
      }
    };

    onMounted(async () => {
      const studentId = route.params.id;
      const studentData = await getStudentData(studentId);
      if (studentData) {
        currentStudent.value = studentData;
        initCharts(studentData);
        initSemesterData(studentData);
        checkPermission(); // 检查权限
      }
    });

    return {
      barChart,
      pieChart,
      lineChart,
      radarChart,
      boxChart,
      heatChart,
      currentStudent,
      addDialogVisible,
      addForm,
      confirmAdd,
      editDialogVisible,
      editForm,
      confirmEdit,
      handleAdd,
      handleEdit,
      deleteForm,
      handleDelete,
      confirmDelete,
      deleteDialogVisible,
      selection,
      Plus,
      Edit,
      Delete,
      DataLine,
      TopRight,
      BottomLeft,
      Collection,
      TrendCharts,
      ArrowUp,
      ArrowDown,
      Reading,
      calculateAverage,
      calculateHighest,
      calculateLowest,
      selectedSemester,
      semesters,
      semesterStats,
      handleSemesterChange,
      handleSubjectSelect,
      semesterOptions,
      handleLogout,
      SwitchButton,
      isTeacher,
      isCurrentStudent,
    };
  }
};
</script>

<style scoped>
.student-grades-container {
  padding: 2rem;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7eb 100%);
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
  padding: 0 1rem;
}

.header-content {
  text-align: left;
}

.header-decoration {
  width: 60px;
  height: 4px;
  background: linear-gradient(90deg, #409EFF, #67C23A);
  margin-top: 0.5rem;
  border-radius: 2px;
}

.button-group {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.button-group .el-button {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.stats-section,
.semester-section,
.info-section,
.charts-section {
  margin-bottom: 2rem;
}

.stat-cards {
  margin-bottom: 0;
}

.stat-card {
  transition: all 0.3s ease;
  border: none;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border-radius: 12px;
  overflow: hidden;
  height: 100%;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.stat-card-content {
  display: flex;
  align-items: center;
  padding: 1.5rem;
  position: relative;
  overflow: hidden;
}

.stat-icon-wrapper {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 1rem;
  transition: all 0.3s ease;
}

.stat-icon-wrapper .el-icon {
  font-size: 28px;
  color: #fff;
}

.stat-icon-wrapper.average {
  background: linear-gradient(135deg, #409EFF 0%, #67C23A 100%);
}

.stat-icon-wrapper.highest {
  background: linear-gradient(135deg, #E6A23C 0%, #F56C6C 100%);
}

.stat-icon-wrapper.lowest {
  background: linear-gradient(135deg, #909399 0%, #606266 100%);
}

.stat-icon-wrapper.total {
  background: linear-gradient(135deg, #409EFF 0%, #909399 100%);
}

.stat-info {
  flex: 1;
}

.stat-label {
  font-size: 0.9rem;
  color: #909399;
  margin-bottom: 0.5rem;
}

.stat-value {
  font-size: 2rem;
  font-weight: 600;
  color: #303133;
  line-height: 1;
  margin-bottom: 0.5rem;
}

.stat-unit {
  font-size: 0.8rem;
  color: #909399;
}

.semester-card,
.info-card,
.chart-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.semester-card:hover,
.info-card:hover,
.chart-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.semester-header,
.info-header,
.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.semester-header h3,
.info-header h3,
.chart-header h3 {
  margin: 0;
  color: #2c3e50;
  font-weight: 500;
}

.semester-stat-item {
  padding: 1.5rem;
  background: #f8f9fa;
  border-radius: 8px;
  text-align: center;
  transition: all 0.3s ease;
}

.semester-stat-item:hover {
  background: #f0f2f5;
  transform: translateY(-2px);
}

.semester-stat-label {
  font-size: 0.9rem;
  color: #909399;
  margin-bottom: 0.5rem;
}

.semester-stat-value {
  font-size: 1.5rem;
  font-weight: 600;
  color: #303133;
}

.chart {
  height: 300px;
  width: 100%;
}

.main-chart {
  height: 100%;
  min-height: 500px;
}

.main-chart-content {
  height: 450px;
}

h1 {
  font-size: 2.2rem;
  color: #2c3e50;
  font-weight: 600;
  margin: 0;
  letter-spacing: 0.5px;
}

.charts-section {
  margin-bottom: 2rem;
}

.main-charts,
.secondary-charts,
.tertiary-charts {
  margin-bottom: 2rem;
}

.chart-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  background: #ffffff;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chart-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 1.5rem;
  border-bottom: 1px solid #ebeef5;
}

.chart-header h3 {
  margin: 0;
  color: #2c3e50;
  font-weight: 500;
  font-size: 1.1rem;
}

.chart-actions {
  display: flex;
  gap: 0.5rem;
}

.chart {
  flex: 1;
  padding: 1rem;
  min-height: 300px;
}

.main-chart {
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
}

.main-chart-content {
  min-height: 450px;
}

.chart-card :deep(.el-card__body) {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 0;
}

.grade-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 0;
}

.grade-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.subject-name {
  font-weight: 500;
  color: #303133;
}

.semester-tag {
  background: #ecf5ff;
  color: #409EFF;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.score-info {
  color: #909399;
  font-size: 13px;
}

:deep(.el-select-dropdown__item) {
  padding: 8px 12px;
}

:deep(.el-select-dropdown__item.selected) {
  background-color: #f5f7fa;
}

:deep(.el-select-dropdown__item:hover) {
  background-color: #f5f7fa;
}

@media (max-width: 768px) {
  .student-grades-container {
    padding: 1rem;
  }

  .page-header {
    flex-direction: column;
    gap: 1rem;
    align-items: flex-start;
  }

  .button-group {
    width: 100%;
    justify-content: space-between;
  }

  .stat-cards .el-col {
    margin-bottom: 1rem;
  }

  .semester-header {
    flex-direction: column;
    gap: 1rem;
  }

  .semester-stat-item {
    margin-bottom: 1rem;
  }

  .charts-section {
    margin-bottom: 1rem;
  }

  .main-charts,
  .secondary-charts,
  .tertiary-charts {
    margin-bottom: 1rem;
  }

  .chart {
    min-height: 250px;
  }

  .main-chart-content {
    min-height: 350px;
  }

  .chart-header {
    padding: 0.75rem 1rem;
  }

  .chart-header h3 {
    font-size: 1rem;
  }
}
</style>
